package it.secse.idmadaption.plugin;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PluginFactory {
	
	static File pluginDir = new File("files");
		
	public static AbstractPlugin newInstance(String OpName){

		File[] fileNames = pluginDir.listFiles();
		int length = fileNames.length;
		for (int i=0; i<length; i++) {
			File file = fileNames[i];
			if (file.getAbsolutePath().endsWith(".config")) {
				Document doc;
				DOMParser parser = new DOMParser();
				try {
					parser.parse(file.getAbsolutePath());
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				doc = parser.getDocument();
				NodeList list = doc.getElementsByTagName("operation");
				
				for (int j=0; j<list.getLength(); j++) {
				    
					System.out.println(list.getLength());
					
					Node node = list.item(j);
					
					if (node.getNodeValue() == null) {
						System.out.println(node.toString());
						
					}
				    
				    if (node.getFirstChild().getNodeValue().equals(OpName)) {
				    	
				    	String className = doc.getElementsByTagName("class").item(0).getFirstChild().getNodeValue();
				    	
				    	try {
							return (AbstractPlugin) Class.forName(className).newInstance();
						} catch (InstantiationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				    }
				    		
					
				}
				
			}
				
				
			
			
		}
		
//		if (OpName.equals("requestMeeting"))
//		return new WSSUSRTokenPlugin();
//		if (OpName.equals("checkSchedule"))
//		return new WSSUSRTokenPlugin();
		return null;
		

		
	}

}
